"""
@file: order.py
@author: yangsiting
@data: 2021/05/01
@desc:
"""
from flask import request, g
from libs.nestable_blueprint import NestableBlueprint
from flask_restful import Api, Resource
from libs.handler import default_error_handler
from models.goods import Goods_info
from models.shop_cart import Shop_cart_Info
from models.orders import Order_Info,Order_User_Info
from models.base import db
from libs.response import generate_response
from serializer.order import order_schema,orders_user_schema
from serializer.goods import good_schema
order_bp = NestableBlueprint('order_v1', __name__, url_prefix='order/')
api = Api(order_bp)

# 指定当出现异常时，所调用的处理方法
# 当需要看到真实的错误信息时，请把下面这一句注释掉
#api.handle_error = default_error_handler

class ToOrderView(Resource):
    #@auth.login_required
    def post(self):
        data = request.json
        goods_id = data["goods_id"]
        user_id = data["user_id"]
        goods_ids = Order_Info.query.filter_by(user_profile_id=user_id).delete()
        db.session.commit()
        for i in goods_id:
            res = Shop_cart_Info.query.filter_by(goods_id=i).first()
            res1 = Goods_info.query.filter_by(goods_id=i).first()
            total = res.goods_num*res1.goods_price
            Order_Info.create_info(user_profile_id=user_id,
                                    goods_id=i,
                                    goods_num=res.goods_num,
                                   goods_price=res1.goods_price,
                                   total_prices = total)
            goods = Shop_cart_Info.query.filter_by(goods_id=i).delete()
            db.session.commit()
        return generate_response(data={'user_id':user_id,"goods_id":goods_id})


class QuerygoodsView(Resource):
    def get(self,user_id):
        goods = Order_Info.query.filter_by(user_profile_id=user_id).all()
        goods_info = []
        for i in goods:
            order_dict = order_schema.dump(i)
            goods_id = i.goods_id
            res = Goods_info.query.filter_by(goods_id=goods_id).first()
            good_dict = good_schema.dump(res)
            order_dict.update(good_dict)
            goods_info.append(order_dict)

        # 编写函数来进行序列化？ => 这一部分大家可以尽情优化~~
        return generate_response(data=goods_info)

class QueryuserView(Resource):
    def get(self,user_id):
        users = Order_User_Info.query.filter_by(user_profile_id=user_id).all()
        users_dict = orders_user_schema.dump(users)
        # 编写函数来进行序列化？ => 这一部分大家可以尽情优化~~
        return generate_response(data=users_dict)


class AddUserView(Resource):
    # @auth.login_required
    def post(self):
        # 获取用户传过来的数据
        data = request.json
        # 验证参数有效性
        # RequestParse: 验证参数类型 => 弱
        # wtforms：更灵活，参数类型、参数值... => 推荐！！
        # 构建表单 => 设置参数的要求 => data与表单绑定 => 验证数据有效性

        Order_User_Info.create_user(user_profile_id=data['user_id'],
                           user_name=data["name"],
                           user_phone=data["phone"],
                           user_addr=data["addr"])
        # user = UserProfile.query.filter_by(user_profile_email=data.get("email")).first()
        # result = user_schema.dump(user)
        # # 返回结果
        return generate_response(data=data)


api.add_resource(ToOrderView, 'addorder/')
api.add_resource(QuerygoodsView, 'querygoods/<user_id>/')
api.add_resource(QueryuserView, 'queryusers/<user_id>/')
api.add_resource(AddUserView,'adduserinfo/')